package flower.com.a600_xm;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import flower.com.a600_xm.adapter.Li_Adapter;
import flower.com.a600_xm.adapter.SynOrder_1_Buy_FragmentAdapter;
import flower.com.a600_xm.bean.MyEvent;
import flower.com.a600_xm.db.Buy_ShoppingInfoDao;
import flower.com.a600_xm.db.Z_ShoppingInfoDao;
import flower.com.a600_xm.db.dbbean.Buy_Shopping;
import flower.com.a600_xm.db.dbbean.Life_Shopping;
import flower.com.a600_xm.ui.NewVersionDialogFragment;
import flower.com.a600_xm.ui.NumberButton;


/**
 * 资产盘点
 */
public class MainActivity extends AppCompatActivity {


    Z_ShoppingInfoDao z_userInfoDao;

    @BindView(R.id.dingweii)
    RelativeLayout dingweii;

    @BindView(R.id.count)
    TextView count;
    @BindView(R.id.qian)
    TextView qian;

    @BindView(R.id.tabs)
    TabLayout tabs;
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.lv)
    ListView lv;

    @BindView(R.id.editText)
    EditText editText;


    List<String> ccList = new ArrayList<String>();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        buy_shoppingInfoDao.deleteUsers();
        EventBus.getDefault().unregister(this);


    }

    Buy_ShoppingInfoDao buy_shoppingInfoDao;
    Li_Adapter li_adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        li_adapter = new Li_Adapter();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        z_userInfoDao = new Z_ShoppingInfoDao(this);
        buy_shoppingInfoDao = new Buy_ShoppingInfoDao(this);
        initview();
        EventBus.getDefault().register(this);
        List<Buy_Shopping> query = buy_shoppingInfoDao.query();
        if (query != null && query.size() > 0) {
            li_adapter.clear();
            li_adapter.addItem(query);
            for (int i = 0; i < query.size(); i++) {
                ccList.add(query.get(i).getName());
            }
            qian.setText(zong());
            count.setText("共" + li_adapter.getdate().size() + "种");
        } else {
            count.setText("共" + 0 + "种");
            qian.setText("合计：￥" + 0 + "元");
        }

        tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 1) {
                    Log.e("77777", "选择了2");
                    MyEvent eventBus = new MyEvent();
                    eventBus.setType("query");
                    eventBus.setName("");
                    EventBus.getDefault().post(eventBus);
                } else {

                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void onEventMainThread(MyEvent event) {

        if (event.getType().equals("add")) {
            String kucun = event.getName();
            Life_Shopping life_shopping = new Life_Shopping();
            life_shopping.setName(kucun);
            life_shopping.setPrice(event.getPrice());
            if (!ccList.contains(kucun)) {
                ccList.add(kucun);
                addshoppig(kucun, event.getPrice(), "1");
                List<Buy_Shopping> query = buy_shoppingInfoDao.query();
                li_adapter.clear();
                li_adapter.addItem(query);
                count.setText("共" + li_adapter.getdate().size() + "种");

                Log.e("zzz", "结果" + all);
                qian.setText(zong());
            }
        } else if (event.getType().equals("dong")) {

            qian.setText(zong());

        }


    }

    public void addshoppig(String name, String Price, String number) {
        buy_shoppingInfoDao.addShopping(name, Price, number);
    }

    public void detleshopping(String name) {
        buy_shoppingInfoDao.deleteUser(name);
    }

    public void removeone(List list, String ST) {
        for (int i = 0; i < list.size(); i++) {

            if (list.get(i).equals(ST)) {

                list.remove(i);

            }

        }
    }

    public String zong() {
        all = 0;
        List<Buy_Shopping> query = buy_shoppingInfoDao.query();
        for (int i = 0; i < query.size(); i++) {
            Buy_Shopping buy_shopping = query.get(i);
            String number = buy_shopping.getNumber();
            String Price = buy_shopping.getPrice();
            double jieguo = Double.valueOf(Price) * Integer.valueOf(number);
            all = all + jieguo;


        }
        return "合计：￥" + String.valueOf(all) + "元";
    }

    public void removeones(final int position, final String name) {


        //发现新版本，提示用户更新
        AlertDialog.Builder alert = new android.support.v7.app.AlertDialog.Builder(this);
        alert.setTitle("提示")
                .setMessage("确定删除此商品？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        removeone(ccList, name);
                        li_adapter.removeItem(position);
                        li_adapter.notifyDataSetChanged();
                        detleshopping(name);
                        qian.setText(zong());
                        count.setText("共" + li_adapter.getdate().size() + "种");
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alert.create().show();

    }


    private void initview() {
        lv.setAdapter(li_adapter);
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Buy_Shopping item = (Buy_Shopping) li_adapter.getItem(i);
                removeones(i, item.getName());

                return true;
            }
        });
        pager.setAdapter(new SynOrder_1_Buy_FragmentAdapter(getSupportFragmentManager(), MainActivity.this));
        tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabs.setupWithViewPager(pager);// 将viewpager和mIndicator关联起来,必须在viewpager设置完adapter后才能调用


    }

    double all = 0;

    @OnClick({R.id.img_back, R.id.buy, R.id.query})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.buy:
                String zong = zong();
                NewVersionDialogFragment newVersionDialogFragment = NewVersionDialogFragment.newInstance("11", "22");
                newVersionDialogFragment.show(getSupportFragmentManager(), "111");
//                Toast.makeText(this, "总价：" + zong, Toast.LENGTH_SHORT).show();

                break;
            case R.id.query:
                pager.setCurrentItem(0);
                new Handler().postDelayed(new Runnable() {
                                              @Override
                                              public void run() {
                                                  MyEvent eventBus = new MyEvent();
                                                  eventBus.setType("query");
                                                  eventBus.setName(editText.getText().toString());
                                                  EventBus.getDefault().post(eventBus);
                                              }
                                          }, 500
                );


                break;


        }
    }


}
